<template>
  <div class="time-down">
    <div class="back">
      <span v-if="this.$route.name!='paperExam'">
        <slot name="ends"></slot>
      </span>
      <span class="timeSpan">{{
        (dayNum * 1 * 24 + hourNum * 1 + "").padStart(2, "0")
      }}</span
      >:<span class="timeSpan">{{ minuteNum }}</span
      >:<span class="timeSpan">{{ secondNum }}</span>
      <span v-if="this.$route.name!='paperExam'">
        <slot name="starts"></slot>
      </span>
    </div>
  </div>
</template>

<script>
import moment from "moment";
export default {
  name: "TimeRangPage",
  props: {
    startStr:"",
    endStr:"",
    startTime: String,
    endTime: String,
  },
  data() {
    return {
      allTime: {
        days: 0,
        hours: 0,
        minutes: 0,
        seconds: 0,
      },
      timeSetInterval: null,
      showTimeDown: false,
      showOver: false,
    };
  },
  watch: {
    allTime: {
      handler(newdata) {
        // 到时间自动触发
        if (
          newdata.days == 0 &&
          newdata.hours == 0 &&
          newdata.minutes == 0 &&
          newdata.seconds == 0
        ) {
          this.$emit("submitPaper");
          clearInterval(this.timeSetInterval1)
        }
      },
      deep: true,
    },
  },
  created() {
    if (moment(new Date()).isBefore(this.startTime)) {
      this.showTimeDown = true;
      this.timeDown();
    }
    if (moment(new Date()).isAfter(this.endTime)) this.showOver = true;
  },
  methods: {
   
    timeDown() {
      this.timeSetInterval1 = setInterval(() => {
        if (moment(this.startTime).isBefore(moment())) {
          this.showTimeDown = false;
          clearInterval(this.timeSetInterval);
          location.reload();
        }
        let dur = moment.duration(moment(this.startTime) - moment(), "ms");
        this.allTime.days = dur.get("days");
        this.allTime.hours = dur.get("hours");
        this.allTime.minutes = dur.get("minutes");
        this.allTime.seconds = dur.get("seconds");
      }, 1000);
    },
  },
  computed: {
    dayNum() {
      if (this.allTime.days < 10) return "0" + this.allTime.days;
      return this.allTime.days;
    },
    hourNum() {
      if (this.allTime.hours < 10) return "0" + this.allTime.hours;
      return this.allTime.hours;
    },
    minuteNum() {
      if (this.allTime.minutes < 10) return "0" + this.allTime.minutes;
      return this.allTime.minutes;
    },
    secondNum() {
      if (this.allTime.seconds < 10) return "0" + this.allTime.seconds;
      return this.allTime.seconds;
    },
  },
};
</script>

<style>
</style>